package org.luxor.commons.elasticsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.luxor.commons.core.utils.StrKit;
import org.luxor.commons.elasticsearch.ElasticClientRest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * ElasticClient 客户端配置
 *
 * @author Mr.Yan  @date 2019/11/21
 */
@Configuration
@EnableConfigurationProperties(ElasticsearchProperties.class)
public class ElasticClientAutoConfig {
    private static final Logger logger = LoggerFactory.getLogger(ElasticClientAutoConfig.class);

    public static final String DEFAULT_INDEX_NAME = "access_log";
    public static final String DEFAULT_TYPE = "default";

    @Resource
    private ElasticsearchProperties properties;


    @Bean("elastic")
    public RestHighLevelClient elasticClient() {
        logger.debug("Initialize RestHighLevelClient Start ...");
        RestHighLevelClient client;
        try {
            String scheme = properties.getProperties().getOrDefault("scheme", "http");
            String[] nodes = properties.getClusterNodes().split(StrKit.COMMA);
            HttpHost[] hosts = new HttpHost[nodes.length];
            for (int i = 0; i < nodes.length; i++) {
                String[] hostAndPost = nodes[i].split(StrKit.COLON);
                hosts[i] = new HttpHost(hostAndPost[0], Integer.parseInt(hostAndPost[1]), scheme);
            }
            client = new RestHighLevelClient(RestClient.builder(hosts));
            logger.info("Initialize RestHighLevelClient Success,bye");
            return client;
        } catch (Exception e) {
            logger.error("Initialize RestHighLevelClient Failure!", e);
            throw e;
        }
    }

    @Bean
    public ElasticClientRest elasticClientRest(RestHighLevelClient elastic) {
        return new ElasticClientRest(elastic);
    }
}
